package com.lekang.le.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lekang.ZcqEntity.*;
import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.common.core.domain.model.LoginUser;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.le.mapper.BillZcqMapper;
import com.lekang.le.service.BillZcqService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log
public class BillZcqServiceImpl implements BillZcqService {
    @Autowired
    private BillZcqMapper billZcqMapper;

    @Override
    public PageInfo<BillInfoDTO> list( String  billNo,String elderlyName,String elderlyIdCard,String transactionStatus,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BillInfoDTO> billInfoDTOPageInfo = billZcqMapper.list(billNo, elderlyName, elderlyIdCard, transactionStatus);
        billInfoDTOPageInfo.forEach(billInfoDTO -> {
            billInfoDTO.setPayDeadline(billInfoDTO.getCreateTime().plusHours(6l));
        });
        PageInfo<BillInfoDTO> pageInfo = new PageInfo<>(billInfoDTOPageInfo);
        return pageInfo;
    }

    @Override
    public BillInfoDTO detail(String billNo) {
        String username = SecurityUtils.getUsername();

        BillInfoDTO billInfoDTO = billZcqMapper.detail(billNo);
        billInfoDTO.setPayDeadline(billInfoDTO.getCreateTime().plusHours(6l));
        billInfoDTO.setCreator( username);
        return billInfoDTO;
    }

    @Override
    public Integer cancel(String billNo) {
        Integer result = billZcqMapper.cancel(billNo);
        return result;
    }

    @Override
    public PageInfo<RefundRecord> refund(RefundRecordQuery refundRecordQuery) {
        PageHelper.startPage(refundRecordQuery.getPageNum(), refundRecordQuery.getPageSize());
        switch (refundRecordQuery.getStatus()){
            case "all":
                break;
            case "processing":
                refundRecordQuery.setStatus("1");
                break;
            case "success":
                refundRecordQuery.setStatus("0");
                break;
            case "fail":
                refundRecordQuery.setStatus("2");
                break;
        }
        List<RefundRecord> refundRecords = billZcqMapper.refund(refundRecordQuery);
        PageInfo<RefundRecord> pageInfo = new PageInfo<>(refundRecords);
        return pageInfo;
    }

    @Override
    public Integer pay(String billNo) {
        Integer result = billZcqMapper.pay(billNo);
        return result;
    }

    @Override
    public List<String> elderlyList() {
        List<String> elderlyList = billZcqMapper.elderlyList();
        return elderlyList;
    }

    @Override
    public List<String> allBilledElderly() {
        List<String> elderlyList = billZcqMapper.allBilledElderly();
        return elderlyList;
    }

    @Override
    public Integer generateMonthly(String elderlyName) {
        // 1. 获取当前登录用户的封装对象（包含用户信息、权限、角色等）
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 2. 从LoginUser中提取用户基本信息（SysUser是若依内置的用户实体类）
        SysUser currentUser = loginUser.getUser();

        // 3. 获取用户关键信息
        long userId = currentUser.getUserId();
        log.info("userId:" + userId);
        Bill bill = new Bill();
       bill.setBillNo("ZCQ" + System.currentTimeMillis());
       bill.setBillType("月度账单");
       bill.setBillMonth("2025-10");
       log.info("fdasfdsafdsa"+elderlyName+elderlyName.length());
        Long elderlyId =    billZcqMapper.getId(elderlyName);
   log.info("elderlyId:" + elderlyId);

        bill.setElderlyId(elderlyId);
        bill.setMonthlyPayable(BigDecimal.valueOf(2305.35));
        bill.setPayableAmount(BigDecimal.valueOf(2605.35));
        bill.setTransactionStatus("已支付");
        bill.setCreator(userId);
        bill.setPrepaymentAmount(BigDecimal.valueOf(5000));
        bill.setCreateTime(LocalDateTime.now());
        bill.setCurrentPayable(BigDecimal.valueOf(2000.05));
        bill.setBillAmount(BigDecimal.valueOf(5000));
        log.info(bill.toString());
        Integer result = billZcqMapper.generateMonthly(bill);
        return result;
    }

    @Override
    public PageInfo<DebtOverdueVo> refundList(String elderlyName, String bedNo, Integer pageNum, Integer pageSize) {
        // 1. 调用原始Mapper查询未分组的原始数据（你的SQL能正常运行，这里不改动）
        PageHelper.startPage(pageNum, pageSize);
        List<DebtOverdueVo> originalList = billZcqMapper.refundList(elderlyName, bedNo);
        PageInfo<DebtOverdueVo> originalPageInfo = new PageInfo<>(originalList);

        // 2. 对原始数据按elderlyName分组：累加金额、取最新截止时间
        Map<String, DebtOverdueVo> groupMap = new HashMap<>();
        for (DebtOverdueVo original : originalList) {
            String name = original.getElderlyName();
            if (groupMap.containsKey(name)) {
                // 已存在该老人：累加金额、更新最新截止时间
                DebtOverdueVo grouped = groupMap.get(name);
                // 累加欠款金额（BigDecimal累加）
                grouped.setDebtAmount(grouped.getDebtAmount().add(original.getDebtAmount()));
                // 取最新的截止时间（比较日期，保留较大的）
                LocalDate currentDeadline = original.getPayDeadline();
                if (currentDeadline.isAfter(grouped.getPayDeadline())) {
                    grouped.setPayDeadline(currentDeadline);
                }
            } else {
                // 不存在该老人：直接放入Map（注意深拷贝，避免修改原始对象）
                DebtOverdueVo newGroup = new DebtOverdueVo();
                newGroup.setElderlyName(original.getElderlyName());
                newGroup.setBedNo(original.getBedNo()); // 床位号取第一个（若有多个可拼接）
                newGroup.setDebtAmount(original.getDebtAmount()); // 初始化金额
                newGroup.setPayDeadline(original.getPayDeadline()); // 初始化时间
                groupMap.put(name, newGroup);
            }
        }

        // 3. 转换分组后的Map为List
        List<DebtOverdueVo> groupedList = new ArrayList<>(groupMap.values());

        // 4. 包装成分页对象（注意：total仍为原始记录数，若需分组后总条数需额外处理）
        PageInfo<DebtOverdueVo> groupedPageInfo = new PageInfo<>(groupedList);
        // 复用原始分页的页码、页大小等信息（仅数据列表替换为分组后的数据）
        groupedPageInfo.setPageNum(originalPageInfo.getPageNum());
        groupedPageInfo.setPageSize(originalPageInfo.getPageSize());
        groupedPageInfo.setTotal(originalPageInfo.getTotal()); // 这里total是原始记录数，若需分组后总数需后端额外查询

        return groupedPageInfo;
    }

    @Override
    public List<BillDetailVoZcq> elderlyBills(String elderlyName) {
        List<BillDetailVoZcq> elderlyBills = billZcqMapper.elderlyBills(elderlyName);
        return elderlyBills;
    }
}



